<template>
  <div class="main member-detail">
    <div class="section">
      <ul class="form-list col-2">
        <li class="form-item">
          <span class="item-title">手机号:</span>
          <p v-text="info.mobile"></p>
        </li>
        <li class="form-item">
          <span class="item-title">性别:</span>
          <p v-text="sexes[info.sex]"></p>
        </li>
        <li class="form-item">
          <span class="item-title">昵称:</span>
          <p v-text="info.nickname"></p>
        </li>
        <li class="form-item">
          <span class="item-title">最后更新时间:</span>
          <p v-text="info.updatedAt"></p>
        </li>
        <li class="form-item">
          <span class="item-title">等级:</span>
          <p>
            <span>{{levels[info.currentMemberCardType]}}</span>
            <span v-if="info.currentMemberCardType > 0&&info.currentMemberCardType < 3">&nbsp;&nbsp;
            {{dateFormatC(formatDate(info.expireDate, 'YYYY-MM-DD HH:mm:ss'))}}{{info.expireDate?'到期':''}}</span>
            <span v-else-if="info.currentMemberCardType!=0">终身</span>
          </p>
        </li>

        <!-- <li class="form-item">
                    <span class="item-title">生日:</span>
                    <p v-text="formatDate(info.birthday, 'YYYY-MM-DD HH:mm:ss')"></p>
        </li>-->
        <li class="form-item">
          <span class="item-title">个性签名:</span>
          <p v-text="info.signature"></p>
        </li>
        <!-- <li class="form-item">
          <span class="item-title">级别:</span>
          <p>
            Lv{{info.subdivisionLevel}}
          </p>
        </li> -->
        <li class="form-item">
          <span class="item-title">心得口号:</span>
          <p class="text-hidden">{{info.userInfoSalesRaking.slogan?info.userInfoSalesRaking.slogan:'主人太懒了，还没来得及写心得口号~'}}</p>
          <p><el-button type="primary" size="mini" @click="toEdit(1)">编辑</el-button></p>
        </li>
        <!-- <li class="form-item">
          <span class="item-title" style="width:110px;">家族累计购买礼包数:</span>
          <p style="text-indent:20px">
            {{info.sangiftCount}}
          </p>
        </li> -->
        <li class="form-item">
          <span class="item-title">心得技巧:</span>
          <p v-if="info.userInfoSalesRaking.experience" v-html="info.userInfoSalesRaking.experience" class="text-border"></p>
          <p v-else>主人太懒了，还没来得及分享心得技巧~</p>
          <p><el-button type="primary" size="mini" @click="toEdit(2)">编辑</el-button></p>
        </li>
        <li class="form-item">
          <span class="item-title">注册时间:</span>
          <p v-text="formatDate(info.createdAt, 'YYYY-MM-DD HH:mm:ss')"></p>
        </li>
        <li class="form-item">
          <span class="item-title">形象照:</span>
          <p>
            <el-upload
              class="avatar-uploader"
              accept="image/*"
              :action="upladUrl"
              name="file"
              :show-file-list="false"
              :on-success="imageSuccess"
              :before-upload="beforeUpload">
              <img v-if="info.userInfoSalesRaking.image_photo_url" :src="info.userInfoSalesRaking.image_photo_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </p>
          <el-button type="primary" size="mini" @click="resetImg">重置</el-button>
        </li>
        <li class="form-item">
          <span class="item-title">最后登录IP:</span>
          <p v-text="info.lastLoginIP"></p>
        </li>
        <li class="form-item">
          <span class="item-title">最后登录时间:</span>
          <p v-text="formatDate(info.lastLoginTime,'YYYY-MM-DD HH:mm:ss')"></p>
        </li>
        <!-- <li class="form-item">
          <span class="item-title" style="width:102px">碧划算预估佣金:</span>
          {{info.bihsTotalFee || 0}}
        </li> -->
        <!-- <li class="form-item">
          <span class="item-title" style="width:102px">累计提现:</span>
          {{info.bihsTotalTakeFee || 0}}
        </li> -->
        <li class="form-item col-1">
          <span class="item-title">用户关系:</span>
          <span @click="getLevelTree">{{info.nickname}}</span>
          <template v-if='levelTree.length > 0'>
            <el-table  border :data="levelTree" style="width: 361px">
                <!-- <el-table-column label="推荐人" prop="parentNickname" width="100"></el-table-column> -->
                <el-table-column label="用户昵称" prop="nickName" width="100"></el-table-column>
                <el-table-column label="手机号码" prop="mobile" width="100"></el-table-column>
                <!-- <el-table-column label="用户等级"  width="80">
                   <span slot-scope="scope">{{oldVipType[scope.row.role]}}</span>
                </el-table-column> -->
                <el-table-column label="用户级别"  prop="level" width="80">
                  <span slot-scope="scope">Lv{{scope.row.level}}</span>
                </el-table-column>
                <el-table-column label="平台等级"  prop="memberLevel" width="80">
                  <span slot-scope="scope">{{levels[scope.row.memberLevel]}}</span>
                </el-table-column>
            </el-table>
            <span style="color:red">*表格下一行为前一行的父级(推荐人)</span>
          </template>
          <!-- <el-tree :props="propsKey" :load="renderTree" lazy></el-tree>
          <span v-if="info.identityPlate">成为皇冠大区时间：{{formatDate(info.identityPlate, 'YYYY-MM-DD HH:mm:ss')}}</span> -->
        </li>
        <!-- <li class="form-item col-1"> -->
          <!-- <span class="item-title">推荐人:</span>
                    <p v-if="info.fatherUserInfo">
                        <svg-icon v-if="info.fatherUserInfo.identityPlate" icon-class="crown" class="crown"></svg-icon>{{info.fatherUserInfo.realName?info.fatherUserInfo.realName:info.fatherUserInfo.nickname}}
                        <el-tag>
          <span>手机号</span>{{info.fatherUserInfo.mobile}}</el-tag>-->
          <!-- <el-tree :props="defaultProps" :data="child" :expand-on-click-node="true" @node-expand="append" node-key="id" lazy :render-content="renderContent"></el-tree> -->
          <!-- <el-menu>
                        <menutree :data="child"></menutree>
          </el-menu>-->
          <!-- </p>
          <p v-else>无相关信息</p>-->
        <!-- </li> -->
        <!-- <li class="form-item col-1">
                    <span class="item-title">大区用户:</span>
                    <p v-if="info.areaUserInfo">
                        <svg-icon v-if="info.areaUserInfo.identityPlate" icon-class="crown" class="crown"></svg-icon>{{info.areaUserInfo.realName?info.areaUserInfo.realName:info.areaUserInfo.nickname}}
                        <el-tag>
                            <span>手机号</span>{{info.areaUserInfo.mobile}}</el-tag>
                    </p>
                    <p v-else>无相关信息</p>
                </li>
                <li class="form-item col-1">
                    <span class="item-title">推荐大区用户:</span>
                    <p v-if="info.recommendAreaUserInfo">
                        <svg-icon v-if="info.recommendAreaUserInfo.identityPlate" icon-class="crown" class="crown"></svg-icon>{{info.recommendAreaUserInfo.realName?info.recommendAreaUserInfo.realName:info.recommendAreaUserInfo.nickname}}
                        <el-tag>
                            <span>手机号</span>{{info.recommendAreaUserInfo.mobile}}</el-tag>
                    </p>
                    <p v-else>无相关信息</p>
                </li>
                <li class="form-item col-1">
                    <span class="item-title">董事:</span>
                    <p v-if="info.directorUserInfo">
                        <svg-icon v-if="info.directorUserInfo.identityPlate" icon-class="crown" class="crown"></svg-icon>{{info.directorUserInfo.realName?info.directorUserInfo.realName:info.directorUserInfo.nickname}}
                        <el-tag>
                            <span>手机号</span>{{info.directorUserInfo.mobile}}</el-tag>
                    </p>
                    <p v-else>无相关信息</p>
                </li>
                <li class="form-item col-1">
                    <span class="item-title">推荐董事:</span>
                    <p v-if="info.recommendDirectorUserInfo">
                        <svg-icon v-if="info.recommendDirectorUserInfo.identityPlate" icon-class="crown" class="crown"></svg-icon>{{info.recommendDirectorUserInfo.realName?info.recommendDirectorUserInfo.realName:info.recommendDirectorUserInfo.nickname}}
                        <el-tag>
                            <span>手机号</span>{{info.recommendDirectorUserInfo.mobile}}</el-tag>
                    </p>
                    <p v-else>无相关信息</p>
        </li>-->
      </ul>
      <div class="btn-center">
        <el-button type="primary" plain @click="$router.go(-1)">返回</el-button>
      </div>
    </div>
    <el-dialog :title="type===1?'心得口号':'心得技巧'" :visible.sync="dialogEdit" width="100%" @close="handleCancel">
      <el-form class="section" :model="formData" :rules="formRules" size="medium" ref="form" label-width="0px">
        <el-form-item label="" prop="slogan" v-if="type===1">
          <el-input type="textarea" :rows="5" placeholder="输入心得口号，4~40个字" v-model="formData.slogan"></el-input>
        </el-form-item>
        <el-form-item label="" prop="experience" v-else>
          <tinymce :height="200" v-model="formData.experience" :id="tinymceId"></tinymce>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="editSure()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import menutree from '@/components/menuTree/index.vue'
import sha1 from 'js-sha1'
import Tinymce from '@/components/Tinymce'
// import { formatDate } from '@/utils/tools'
export default {
  components: {
    menutree,
    Tinymce
  },
  name: 'memberDetail',
  props: {
    id: {
      default: ''
    }
  },
  data() {
    return {
      tinymceId: 'vue-tinymce-' + +new Date(),
      formRules: {
        slogan: [
          {required: true, message: '不能为空', trigger: 'change'},
          {min: 4, message: '不能小于4个字', trigger: 'change'},
          {max: 40, message: '不能超过40个字', trigger: 'change'}
        ],
        experience: [
          {required: true, message: '不能为空', trigger: 'change'},
          {min: 6, message: '不能小于6个字', trigger: 'change'}
        ]
      },
      formData: {
        experience: '',
        slogan: ''
      },
      dialogEdit: false, // 编辑心得和宣传口号
      type: 0, // 1心得口号2心得技巧
      levelTree: [], // 用户关系层级
      // 基本信息
      info: {
        userInfoSalesRaking:{
          slogan: '',
          experience: '',
          image_photo_url: ''
        }
      },
      treeData: {},
      child: [],
      isChild: true,
      // 性别
      sexes: {
        '0': '保密',
        '1': '男',
        '2': '女'
      },
      // 会员等级
      levels: {},
      levelsOld: {},
      loading: false,
      propsKey: {
        label: 'nickname'
      },
      defaultProps: {
        label: 'name'
      }
    }
  },
  created() {
    this.getInfo()
    //获取会员等级
    this.levels = this.$enum.vipGrade
    this.oldVipType = this.$enum.oldVipType
  },
  methods: {
    dateFormatC(dateStr) {
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour =  date.getHours()
      const minute = date.getMinutes()
      return year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
    },
    // 弹框取消
    handleCancel () {
      if (this.type === 1) {
        this.$set(this.formData, 'slogan', '')
      } else {
        if (window.tinymce.get(this.tinymceId)) {
          window.tinymce.get(this.tinymceId).setContent('')
        }
        this.$set(this.formData, 'experience', '')
      }
      this.dialogEdit = false
    },
    // 重置图片按钮
    resetImg () {
      this.info.userInfoSalesRaking.image_photo_url = ''
      this.editRequest()
    },
    editRequest () {
      this.request({
        url: '/bsnl-member/member/sales-ranking/save',
        method: 'post',
        data: {
          experience: this.formData.experience?this.formData.experience:this.info.userInfoSalesRaking.experience,
          image_photo_url: this.info.userInfoSalesRaking.image_photo_url,
          slogan: this.formData.slogan?this.formData.slogan:this.info.userInfoSalesRaking.slogan,
          targetUserId:this.info.userId
        }
      }).then(({ data }) => {
        this.info.userInfoSalesRaking = { ...data }
        this.dialogEdit = false
      }).catch(err => {
        this.info.userInfoSalesRaking = {
          experience: '主人太懒了，还没来得及分享心得技巧~',
          image_photo_url: '',
          slogan: '主人太懒了，还没来得及写心得口号~'
        }
      })
    },
    // 编辑心得口号和心得技巧
    editSure () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.formData.experience&&this.formData.experience.length < 241) {
            this.$message.error('心得技巧不少于6个字')
            return
          }
          this.editRequest()
        }
      })
    },
    // 编辑1心得口号2心得技巧
    toEdit (type) {
      this.type = type
      this.$set(this.formData, 'slogan', this.info.userInfoSalesRaking.slogan!=='主人太懒了，还没来得及写心得口号~'?this.info.userInfoSalesRaking.slogan:'')
      this.$set(this.formData, 'experience', this.info.userInfoSalesRaking.experience!=='主人太懒了，还没来得及分享心得技巧~'?this.info.userInfoSalesRaking.experience:'')
      this.dialogEdit = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 形象照上传成功
    imageSuccess (res, file) {
      this.info.userInfoSalesRaking.image_photo_url = this.replaceImgUrl(res.filePath)
      this.editRequest()
    },
    // 获取列表
    getInfo() {
      this.request({
        url: `/bsnl-member/member/${this.id}/load`,
        method: 'get'
      })
        .then(({ data }) => {
          this.info = { ...data }
          this.$nextTick(() => {
            this.child = this.custmizeData(data)
          })

          // this.child.push({ label: data.});
          // if (this.isChild) {
          //     this.treeData.push(data);
          // }
        })
        .catch(err => {
          this.info = {}
        })
    },
    getInfo2(node, resolve) {
      this.request({
        url: `/bsnl-member/member/${this.id}/load`,
        method: 'get'
      })
        .then(({ data }) => {
          resolve([data])
        })
        .catch(err => {
          resolve([])
        })
    },
    // 获取用户关系层级数
   async getLevelTree() {
     if(this.levelTree.length > 0) {
       return
     }
       //时间挫
    let stamp = new Date().getTime()
        //随机6位数
    let nonce = Math.floor(Math.random() * 999999)
    let bb ='ojojioji:;;?@#-=UFJHFUfehu!SNJHUFp[][d' + stamp + nonce
    let sign = sha1(bb)
     try {
       const {data} = await this.request({
          url: `/api/customer/v1/open/bx/user/level/link?uid=${this.info.userId}`,
          method: 'get',
          headers: {
            sign: sign,
            stamp: stamp,
            nonce: nonce,
          },
       })

       this.levelTree = data.parentList
       this.levelTree.unshift({
         parentNickname: data.parentNickname,
         nickName: data.nickName,
         role: data.role,
         level: data.level,
         mobile: data.mobile,
         memberLevel: data.memberLevel
       })
       console.log('dataaa', data)
     } catch (error) {
       console.log(error)
     }
    },
    custmizeData(data) {
      let res = []
      if (data.fatherUserInfo) {
        res.push({
          index: 1,
          uId: data.fatherUserInfo.id,
          label: data.fatherUserInfo.realName
            ? data.fatherUserInfo.realName
            : data.fatherUserInfo.nickname,
          mobile: data.fatherUserInfo.mobile,
          name: '推荐人: ',
          crown: data.fatherUserInfo.identityPlate
            ? this.formatDate(
                data.fatherUserInfo.identityPlate,
                'YYYY-MM-DD HH:mm:ss'
              )
            : ''
        })
      } else {
        res.push({
          index: 1,
          uId: null,
          label: '无相关信息',
          mobile: '',
          name: '推荐人: '
        })
      }
      if (data.areaUserInfo) {
        res.push({
          index: 2,
          uId: data.areaUserInfo.id,
          label: data.areaUserInfo.realName
            ? data.areaUserInfo.realName
            : data.areaUserInfo.nickname,
          mobile: data.areaUserInfo.mobile,
          name: '大区用户: '
        })
      } else {
        res.push({
          index: 2,
          label: '无相关信息',
          mobile: '',
          name: '大区用户: '
        })
      }

      if (data.recommendAreaUserInfo) {
        res.push({
          index: 3,
          uId: data.recommendAreaUserInfo.id,
          label: data.recommendAreaUserInfo.realName
            ? data.recommendAreaUserInfo.realName
            : data.recommendAreaUserInfo.nickname,
          mobile: data.recommendAreaUserInfo.mobile,
          name: '推荐大区用户: '
        })
      } else {
        res.push({
          index: 3,
          label: '无相关信息',
          mobile: '',
          name: '推荐大区用户: '
        })
      }
      if (data.directorUserInfo) {
        res.push({
          index: 4,
          uId: data.directorUserInfo.id,
          label: data.directorUserInfo.realName
            ? data.directorUserInfo.realName
            : data.directorUserInfo.nickname,
          mobile: data.directorUserInfo.mobile,
          name: '董事: '
        })
      } else {
        res.push({ index: 4, label: '无相关信息', mobile: '', name: '董事: ' })
      }
      if (data.recommendDirectorUserInfo) {
        res.push({
          index: 5,
          uId: data.recommendDirectorUserInfo.id,
          label: data.recommendDirectorUserInfo.realName
            ? data.recommendDirectorUserInfo.realName
            : data.recommendDirectorUserInfo.nickname,
          mobile: data.recommendDirectorUserInfo.mobile,
          name: '推荐董事: '
        })
      } else {
        res.push({
          index: 5,
          label: '无相关信息',
          mobile: '',
          name: '推荐董事: '
        })
      }
      return res
    },
    showMore(id, node) {
      if (id) {
        this.getInfo2(id)
      }
    },
    append(source, node) {
      console.log(node)
      node.loading = true
      if (!source.children) {
        this.$set(source, 'children', [])
      }
      if (source.uId) {
        this.request({
          url: `/bsnl-member/member/${source.uId}/load`,
          method: 'get'
        })
          .then(({ data }) => {
            let x = this.custmizeData(data)
            if (!source.children.length > 0) {
              source.children = x
            }
            node.loading = false
          })
          .catch(err => {
            console.log(err)
            node.loading = false
            node.isLeaf = true
          })
      } else {
        node.loading = false
        node.isLeaf = true
      }
    },
    renderContent(h, { node, data, store }) {
      return (
        <div style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span style="display:block;position:relative">
            <span>
              {data.name + ''} {data.label}
            </span>{' '}
            <span>
              {' '}
              {data.mobile !== '' ? '手机号：' : ''} {data.mobile}{' '}
              {data.crown ? '成为皇冠时间：' + data.crown + ' 👑  ' : ''}
            </span>
          </span>
          <span></span>
        </div>
      )
    },

    // 获取关系树
    // renderTree(node, resolve) {
    //   if (node.level > 0) {
    //     this.request({
    //       url: `/bsnl-member/member/${node.id}/findById`,
    //       method: 'get'
    //     })
    //       .then(({ data }) => {
    //         let arr = data ? data : []
    //         if (arr.identityPlate) {
    //           arr.nickname = arr.nickname + ' 👑 '
    //         }
    //         resolve(arr)
    //       })
    //       .catch(err => {
    //         resolve([])
    //       })
    //   } else if (node.level === 0) {
    //     this.request({
    //       url: `/bsnl-member/member/${this.id}/load`,
    //       method: 'get'
    //     })
    //       .then(({ data }) => {
    //         let arr = data
    //         if (arr.identityPlate) {
    //           arr.nickname = arr.nickname + ' 👑 '
    //         }
    //         resolve([arr])
    //       })
    //       .catch(err => {
    //         resolve([])
    //       })
    //   }
    // }
  }
}
</script>
<style lang="scss" scoped>
.crown {
  color: #ffc100;
  margin-right: 8px;
  width: 1.2em;
  height: 1.2em;
}
.el-tree-node__content {
  height: auto !important;
}
.item-title {
  white-space: nowrap;
}
.form-item{
  flex: 0 0 47%!important;
}
.text-hidden {
  line-height: 1.12;
  white-space: normal;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  line-clamp: 4;
  -webkit-box-orient: vertical;
}
.text-border {
  height: 120px;
  overflow: auto;
  border: 1px solid #ddd;
  padding: 0 10px;
}
</style>
